package com.aaa.filter;

import com.aaa.result.Result;
import com.aaa.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TokenFilter implements GlobalFilter, Ordered {
    @Value("${loginURI}")
    private String loginURI;
    @Value("${Download}")
    private String Download;

    @Autowired
    private AuthService service;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1,验证请求是否需要验证token（登陆不需要验证token）
        URI uri = request.getURI();
        if (uri.getPath().contains(loginURI)){
            //放行
            return chain.filter(exchange);
        }
        if (uri.getPath().contains(Download)){
            //放行
            return chain.filter(exchange);
        }

        //2，验证请求中是否有token
        //3，如果没有，返回，需要携带token 认证
        List<String> accessToken = request.getHeaders().get("accessToken");
       if (  accessToken==null||accessToken.size()==0){
           response.setStatusCode(HttpStatus.UNAUTHORIZED);
           //指定编码，否则在浏览器中会中文乱码
           response.getHeaders().add("Content-Type", "text/json;charset=UTF-8");
           Map<String,String> message = new HashMap<String, String>();
           message.put("code", "401");
           message.put("message", "没有token");
           byte[] bits = message.toString().getBytes();
           DataBuffer buffer = response.bufferFactory().wrap(bits);
           return response.writeWith(Mono.just(buffer));
       }


        //4，如果有 则验证token的正确性(使用feijn把token给认证项目)
        String token = accessToken.get(0);
        String ipAddr = request.getRemoteAddress().getHostString();
       //将token交给 认证项目
        Result result = service.authToken(token, ipAddr);
        if (result.getCode() == 1){
            return chain.filter(exchange);
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/json;charset=UTF-8");

        //5，如果有毛病 则返回信息,没有问题就放行
        Map<String,String> message = new HashMap<>();
        message.put("code", "404");
        message.put("message", "token有问题");
        byte[] bits = message.toString().getBytes();
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
